import settings from '../settings'
import axios from 'axios'
import { Toast } from 'vant'
import router from '../router'

// 传输cookies
axios.defaults.withCredentials = true

var service = axios.create({
  baseURL: settings.target,
  timeout: 30000
})


service.interceptors.request.use((config) => {
  // npgrogress.start()
  config.headers['token'] = localStorage.getItem('token')
  return config
})

service.interceptors.response.use((res) => {
  console.log(res)
  const data = res.data
  if (data.code !== 200) {
    if (data.code === 401 || data.code === 403) {
      Toast('身份认证已过期，请重新登录')
      localStorage.removeItem('token')
      router.replace({ path: '/login' })
    } else {
      Toast(data.message)
    }
    return Promise.reject(data.message)
  } else {
    return data
  }
}, (err) => {
  Toast(err.message)
})

export default function request(data) {
  if (data.method.toLowerCase() === 'get') {
    data.params = data.data
    delete data.data
  }
  return service(data)
}

